<?php
namespace App\Model;
use PhalApi\Model\NotORMModel as NotORM;

class Vip extends NotORM {
	
	/* VIP列表 */
	public function getVip() {
		
		$rules=\PhalApi\DI()->notorm->vip
				->select('*')
				->order('list_order asc')
				->fetchAll();

		return $rules;
	}
    
    /* 我的VIP */
	public function myVip($uid) {
		
		$info=\PhalApi\DI()->notorm->vip_user
				->select('*')
				->where('uid=?',$uid)
				->fetchOne();

		return $info;
	}
    
    /* 添加VIP */
	public function setVip($data) {
		
		$rs= \PhalApi\DI()->notorm->vip_user->insert($data);

		return $rs;
	}		

	/* 更新VIP */
	public function upVip($uid,$data) {

		$rs= \PhalApi\DI()->notorm->vip_user
                    ->where('uid = ? ', $uid)
                    ->update( $data );

		return $rs;
	}
    
    /* VIP订单 */
	public function setOrder($data) {

		$rs= \PhalApi\DI()->notorm->vip_order->insert( $data );

		return $rs;
	}
	
	public function updatePaymentStatus($uid,$nonce,$orderid,$money) {
			 
		$orderinfo=\PhalApi\DI()->notorm->vip_order->where('orderno=? and money=? ',$orderid,$money)->fetchOne();
		
		
		if($orderinfo){
			
			if($orderinfo['status']==0){
				/* 更新VIP */
				$length=$orderinfo['length'];
				$addtime=time();
				
				$vip=\PhalApi\DI()->notorm->vip_user->where('uid=? ',$orderinfo['uid'])->fetchOne();
				if(!$vip){
					/* 未购买过 */
					$data=[
						'uid'=>$orderinfo['uid'],
						'addtime'=>$addtime,
						'endtime'=>$addtime + $length,
					];
					\PhalApi\DI()->notorm->vip_user->insert($data);
				}else if($vip['endtime']< $addtime){
					/* 购买-已过期 */
					$data=[
						'addtime'=>$addtime,
						'endtime'=>$addtime + $length,
					];
					\PhalApi\DI()->notorm->vip_user->where('uid=? ',$orderinfo['uid'])->update($data);
				}else{
					/* 续费 */
					$data=[
						'addtime'=>$addtime,
						'endtime'=>$vip['endtime'] + $length,
					];
					\PhalApi\DI()->notorm->vip_user->where('uid=? ',$orderinfo['uid'])->update($data);
				}
				
				/* 更新 订单状态 */
				\PhalApi\DI()->notorm->vip_order->where('id=? ',$orderinfo['id'])->update(array("status"=>1,"trade_no"=>$nonce));
			}else{
				return 0;
			}
		}else{
			return 1003;	
		}
		
		return 0;
	}

}
